<?php

namespace app\api\service\user;

use app\model\user\UserDynamicsModel;
use app\model\user\UserModel;
use app\service\ai\DeepseekClient;
use hunma\exception\ApiException;

class UserDynamicsService
{
    public function dynamic()
    {
        // 获取最早更新的用户
        $user = UserModel::getOne([],['id', 'character','account','update_num'],['update_time' => 'asc']);

        $ai = new DeepseekClient();
        $markdownData = $ai->chat($user['character']."。请生成20条积极向上的中文动态内容，符合用户性格特点，以json的格式只返回内容的文本，内容自动换行，其他都不要。例子：{['xxxxxx','xxxxxx']}");
        // 判断是否为Markdown代码块格式
        if(preg_match('/```json\n.*\n```/s', $markdownData)) {
            $markdownData = preg_replace('/```json\n|\n```$/', '', $markdownData);
        }

        $markdownData = preg_replace('/^\s*{\s*(\[.*\])\s*}\s*$/s', '$1', $markdownData);

        if (!preg_match('/^\s*\[.*\]\s*$/s', $markdownData)) {
            // 如果还不是有效的数组格式，尝试提取数组部分
            if (preg_match('/\[(.*)\]/s', $markdownData, $matches)) {
                $markdownData = '[' . $matches[1] . ']';
            }
        }

        $posts = json_decode($markdownData, true);

        if(!is_array($posts) || empty($posts)) {
            // 如果解析失败，尝试手动解析
            $posts = [];
            if (preg_match_all('/"([^"]+)"/', $markdownData, $matches)) {
                $posts = $matches[1];
            }

            if(empty($posts)) {
                throw new ApiException('找不到数据');
            }
        }

        $aData = [
          'user_id' => $user['id']
        ];
        foreach ($posts as $k=>$v){
            $aData['content'] = $v;
            UserDynamicsModel::add($aData);
        }

        // 更新用户时间
        UserModel::edit(['id'=>$user['id'],'update_num'=>$user['update_num']+1]);

        return $posts;
    }

    public function list(array $getAllParams)
    {
        $getAllParams['page'] = isset($getAllParams['page']) ? (int)$getAllParams['page'] : 1;
        $getAllParams['limit'] = isset($getAllParams['limit']) ? (int)$getAllParams['limit'] : 200;

        $where = [];
        if(isset($getAllParams['user_id']) && !empty($getAllParams['user_id'])){
            $where[] = ['user_id', '=', $getAllParams['user_id']];
        }

        if(isset($getAllParams['review_status']) && $getAllParams['review_status'] != ''){
            $where[] = ['review_status', '=', (int)$getAllParams['review_status']];
        }else{
            $where[] = ['review_status', '=', 0]; // 默认只获取未审核通过的
        }

        return UserDynamicsModel::getList($where, ['id' => 'desc'],['id', 'content', 'create_time'],  $getAllParams['page'], $getAllParams['limit']);
    }

    public function audit(array $params)
    {
        // 批量审核
        $data = [
            'review_status' => (int)$params['status'],
        ];
        if (isset($params['remark'])) {
            $data['remark'] = $params['remark'];
        }
        $res = UserDynamicsModel::whereIn('id', $params['ids'])->update($data);
        if ($res === false) {
            throw new ApiException('批量审核失败');
        }
        return true;
    }

    public function edit(array $params)
    {
        $data = [
            'content' => $params['content'],
            'review_status' => 0, // 编辑后需要重新审核
        ];
        $res = UserDynamicsModel::where('id', $params['id'])->update($data);

        if($res === false){
            throw new ApiException('编辑失败');
        }

        return true;
    }


}